var express = require('express');
var router = express.Router();
const shsDB = require("../db/index.js");
const addOperationLog = require('./../utils/operationLog/index.js');
/**
 * @param {Object} 获取联系人
 * @param {Object} res
 * @param {Object} req.param.fromId 用户id
 */
router.get('/userList', jwtVerify, function(req, res, next) {
	let Item = req.query;
	let obj = {
		code: 200,
		message: "",
		data: {
			message: "", //业务消息
		}
	}
	Item.fromId = req.shsImUserInfo.fromId ? req.shsImUserInfo.fromId : Item.fromId
	if (!Item.fromId) {
		obj.message = "未按要求传参[缺少用户fromId]";
		obj.code = 201;
		res.end(JSON.stringify(obj));
		return;
	}
	//查询联系人列表
	let select =
		`select resh.Id,resh.otherId,users.username as otherName,users.url as otherUrl,users.gender,users.status,resh.createTime,resh.updateTime,resh.updateTime as lastTime,resh.lastMessage,resh.bacImage  from relationshipuser as resh left join users on users.Id=resh.otherId where resh.userId='${Item.fromId}' and resh.status=1`;
	shsDB(select).then(data => {
		if (data.length > 0) {
			for (let i = 0; i < data.length; i++) {
				data[i].isGroup = 0;
				data[i].isActive = 0;
			}
		}
		obj.data = data
		// 查询用户所在群聊列表
		// let groupWhiteList=[] shsgroup.Id=1 or 
		select =
			`select shsgroup.Id,shsgroup.Id as otherId ,shsgroup.groupname as otherName,
			shsgroup.url as otherUrl,glm.lastMessage,glm.updateTime as lastTime,shsgroup.userlist,
			shsgroup.status,shsgroup.describe,shsgroup.createTime,shsgroup.updateTime ,shsgroup.isneed as isneed
			from shsgroup 
			left join grouplastmsg as glm on glm.groupId=shsgroup.Id  
			where shsgroup.isneed=1 
			or shsgroup.userlist like "%${Item.fromId},%"
			or shsgroup.userlist like "%${Item.fromId}"
			or shsgroup.userlist = "${Item.fromId},"
			 and shsgroup.status=1`
		return shsDB(select);
	}).then(data => {
		if (data.length > 0) {
			for (let i = 0; i < data.length; i++) {
				data[i].isGroup = 1;
				data[i].isActive = 0;
				if (data[i].Id === 1) {
					data[i].isActive = 1;
				}
			}
			for (let i = 0; i < data.length; i++) {
				obj.data.push(data[i])
			}
			//按时间先后排序
			try {
				obj.data.sort((a, b) => {
					return new Date(b.lastTime) - new Date(a.lastTime)
				})
			} catch (e) {
				console.log("时间排序处理错误", err)
			}
		}
		res.json(obj);
	}).catch(err => {
		obj.code = 201;
		obj.message = err.message;
		res.json(obj);
	})
});

/**
 * @param {Object} 获取新好友请求列表 
 * status 只显示未处理 在有效期的
 * @param {Object} req.param.fromId 用户id
 */
router.get('/contactUntreated', jwtVerify, function(req, res, next) {
	try {
		let fromId = req.shsImUserInfo.fromId;
		let obj = {
			code: 200,
			message: "",
			data: {
				message: "", //业务消息
			}
		}

		let selectSql =
			`select count(*) as count from contact where userId=${fromId} and isAgree=0 and status=1; `
		shsDB(selectSql).then(data => {
			obj.message = 'success'
			obj.data = data[0]
			res.json(obj);
		}).catch(err => {
			obj.code = 201;
			obj.message = err.message;
			res.json(obj);
		})
	} catch (e) {
		res.json(e.message);
	}
});
/**
 * @param {Object} 获取好友请求列表
 * @param {Object} res
 * @param {Object} req.param.fromId 用户id
 */
router.get('/contactList', jwtVerify, function(req, res, next) {
	try {
		let Item = req.query;
		let obj = {
			code: 200,
			message: "",
			data: {
				message: "", //业务消息
			}
		}
		Item.fromId = req.shsImUserInfo.fromId
		if (!Item.fromId) {
			obj.message = "未按要求传参[缺少用户Id]";
			obj.code = 201;
			res.end(JSON.stringify(obj));
			return;
		}
		let pageSizes = Item.pageSizes || 10; //条数
		let pageNum = Item.pageNum || 1; //第几页
		let pageStart = pageSizes * (pageNum - 1); //pageSizes*(pageNum-1)
		let selectSql = `select cta.contactId,cta.userId,users.username,users.url,cta.otherId,cta.otherUsername,cta.otherUrl,cta.msg,cta.isAgree,cta.status,cta.createTime,cta.updateTime 
			from( select * from contact where userId=${Item.fromId} or otherId=${Item.fromId} ORDER BY createTime desc )as cta
	left join users on users.Id=cta.userId ORDER BY createTime desc limit ${pageStart},${pageSizes}; `
		shsDB(selectSql).then(data => {
			obj.data = data
			res.json(obj);
		}).catch(err => {
			obj.code = 201;
			obj.message = err.message;
			res.json(obj);
		})
	} catch (e) {
		//TODO handle the exception
	}
});

/**
 * @param {Object} 添加好友请求
 * @param {Object} res
 * @param {Object} req.body.fromId 用户id
 */
router.post('/creatContact', jwtVerify, function(req, res, next) {
	let Item = req.body;
	let obj = {
		code: 200,
		message: "",
		data: {
			message: "", //业务消息
		}
	}
	Item.fromId = req.shsImUserInfo.fromId
	Item.fromUsername = req.shsImUserInfo.fromName;
	Item.fromUrl = req.shsImUserInfo.fromUrl;
	if (!Item.fromId || !Item.otherId || !Item.fromUsername || !Item.fromUrl) {
		obj.message = "未按要求传参";
		obj.code = 201;
		res.end(JSON.stringify(obj));
		return;
	}
	//查看是否是联系人
	let selectSql =
		`select count(*) as count from relationshipuser where (userId=${Item.fromId} and otherId=${Item.otherId}) or (userId=${Item.otherId} and otherId=${Item.fromId}) and status=1`;
	shsDB(selectSql).then(data => {
		if (data[0].count) {
			obj.message = "已添加";
			throw new Error(JSON.stringify(obj))
		}
		//查看是否已申请且未通过
		selectSql =
			`select count(*) as count from contact as cta where userId=${Item.otherId} and otherId=${Item.fromId} and isAgree=0  and status=1`
		return shsDB(selectSql)
	}).then(data => {
		if (data[0].count) {
			obj.message = "发送成功,不要频繁请求啦 亲~";
			throw new Error(JSON.stringify(obj))
		}
		//userId被添加  otherId添加的人
		let insertSql =
			`insert into contact(contactId,userId,otherId,otherUsername,otherUrl,msg,isAgree,status,createTime,updateTime)
		values(null,${Item.otherId},${Item.fromId},'${Item.fromUsername}','${Item.fromUrl}','${Item.msg|| "请求添加你为好友"}',0,1,Now(),Now())`

		return shsDB(insertSql)
	}).then(data => {
		if (data.affectedRows != 1) {
			obj.message = "请求发送失败";
			throw new Error(JSON.stringify(obj))
		}
		obj.message = "发送成功";
		let send = {
			code: 200,
			message: "好友添加请求",
			type: 2,
			fromUsername: Item.fromUsername,
			fromId: Item.fromId,
		}

		if (wsClients[Item.otherId] !== undefined) {
			wsClients[Item.otherId].forEach((client) => {
				client.send(JSON.stringify(send));
			});
		}
		res.json(obj);
		try {
			upIntegral(Item.fromId, 2)
		} catch (e) {
			//TODO handle the exception
		}
	}).catch(err => {
		let msg = JSON.parse(err.message).message
		if (msg === "发送成功" || msg === "发送成功,不要频繁请求啦 亲~") {
			res.json(obj);
			return;
		}
		obj.code = 201;
		obj.message = err.message;
		res.json(obj);
	})

});

/**
 * @param {Object} 处理好友请求
 * @param {Object} res
 * @param {Object} req.body.contactId  !Item.contactId || !Item.fromId || !Item.otherId || !Item.fromName
 */
router.post('/ContactAgree', jwtVerify, function(req, res, next) {
	let Item = req.body;
	let obj = {
		code: 200,
		message: "",
		data: {
			message: "", //业务消息
		}
	}
	Item.fromId = req.shsImUserInfo.fromId
	Item.fromName = req.shsImUserInfo.fromName
	if (!Item.contactId || !Item.fromId || !Item.otherId || !Item.fromName) {
		obj.message = "未按要求传参";
		obj.code = 201;
		res.end(JSON.stringify(obj));
		return;
	}
	//检查数据是否已经处理过
	let selectSql =
		`select count(*) as count from relationshipuser where ((userId=${Item.fromId} and otherId=${Item.otherId}) or (userId=${Item.otherId} and otherId=${Item.fromId})) and status=1`;
	shsDB(selectSql).then(data => {
		if (data[0].count) {
			obj.message = "已添加";
			throw new Error(JSON.stringify(obj))
		}
		let updateSql =
			`update contact set isAgree=1 where ((userId= ${Item.fromId} and otherId=${Item.otherId} ) or (userId= ${Item.otherId}  and otherId=${Item.fromId})) and status=1 and isAgree=0 ` // contactId=${Item.contactId}
		return shsDB(updateSql)
	}).then(data => {
		if (data.affectedRows != 1 && data.affectedRows != 2) {
			obj.message = "操作失败，请稍后再试";
			throw new Error(JSON.stringify(obj))
		}
		let insql =
			`insert into relationshipuser(Id,userId,otherId,status,createTime,updateTime,lastMessage,bacImage) value(null,${Item.fromId},${Item.otherId},1,Now(),Now(),'',''),(null,${Item.otherId},${Item.fromId},1,Now(),Now(),'','')`
		return shsDB(insql);
	}).then(data => {
		if (data.affectedRows != 2) {
			obj.message = "操作失败，请稍后再试";
			throw new Error(JSON.stringify(obj))
		}
		//发送给发起添加的提醒
		let send = {
			code: 200,
			message: "同意你的好友请求",
			type: 4,
			fromId: Item.fromId,
			userId: Item.otherId, //被同意者id
			fromUsername: Item.fromName //同意者名称
		}
		if (wsClients[Item.otherId] !== undefined) {
			wsClients[Item.otherId].forEach((client) => {
				client.send(JSON.stringify(send));
			});
		}

		obj.code = 200;
		send.message = obj.message = "添加成功";
		res.json(obj);
		// 多点登录 推送
		if (wsClients[Item.fromId] !== undefined) {
			wsClients[Item.fromId].forEach((client) => {
				client.send(JSON.stringify(send));
			});
		}
		try {
			upIntegral(Item.fromId, 2)
		} catch (e) {
			//TODO handle the exception
		}
	}).catch(err => {
		obj.code = 201;
		obj.message = err.message;
		res.json(obj);
	})
});
/**
 * @param {String} req = [deleter,deletedContact]删除者和被删除者
 */
router.post('/DeleteContact', jwtVerify, function(req, res, next) {
	let Item = req.body;
	try {
		if (!Item.deleter || !Item.deletedContact) {
			res.send(JSON.stringify({
				code: 201,
				message: "未按要求传参[deleter,deletedContact]删除者和被删除者"
			}))
			return;
		}
		let delSql = 'DELETE FROM relationshipuser WHERE (userId=? AND otherId=?) OR (userId=? AND otherId=?)';
		let updateSql =
			'UPDATE contact SET status=4 WHERE ((userId=? AND otherId=?) OR (userId=? AND otherId=?) ) and status=1 ';
		shsDB(delSql, [Item.deleter, Item.deletedContact, Item.deletedContact, Item.deleter]).then(data => {
			addOperationLog(Item.deleter, '删除好友', 'relationshipuser', Item.deleter + "--" + Item
				.deletedContact, "删除成功", null)
			return shsDB(updateSql, [Item.deleter, Item.deletedContact, Item.deletedContact, Item
				.deleter
			])
		}).then(data => {
			res.send(JSON.stringify({
				code: 200,
				message: "删除成功",
				deleter: Item.deleter,
				deletedContact: Item.deletedContact
			}))
			// 给指定id发送数据
			WSsendMessage({
				type: 99,
				code: "deletecontact",
				deleter: Item.deleter,
				deletedContact: Item.deletedContact
			}, Item.deleter)
			WSsendMessage({
				type: 99,
				code: "deletecontact",
				deleter: Item.deleter,
				deletedContact: Item.deletedContact
			}, Item.deletedContact)
			addOperationLog(Item.deleter, '删除好友', 'contact', Item.deleter + "--" + Item.deletedContact,
				'status:1', 'status:4')
		}).catch(err => {
			res.send(JSON.stringify({
				code: 500,
				message: err.message
			}))
			addOperationLog(Item.deleter, '删除好友--err', 'relationshipuser and contact',
				Item.deleter + "--" + Item.deletedContact,
				err.message, null)
		})
	} catch (err) {
		res.send(JSON.stringify({
			code: 500,
			message: err.message
		}))
		addOperationLog(Item.deleter, '删除好友--err', 'relationshipuser and contact',
			Item.deleter + "--" + Item.deletedContact,
			err.message, null)
	}
})


module.exports = router;